<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Examination extends MY_Luckydog
{
	public function __construct()
	{
		parent::__construct();
      /*  $func = $this->router->fetch_method();
        if($func != "upload_cover"){
            $login_status = $this->check_login_status();
            if ($login_status === FALSE){
                header("Location:login");
            }
        }*/
        $this->load->model('luckydog/Examination_model', 'examination');
        $this->load->model('luckydog/Point_model', 'point');
	}


    public function index()
    {
        $_SESSION['v_menu'] = 'examination';
        $per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 0;
        $limit = 20;
        $examinationList = $this->examination->getExaminationList($per_page, $limit);
        $total_rows = $this->examination->getExaminationListCnt();
        $base_url = '/luckydog/examination/index?';
        $page_links = $this->create_page_links($base_url,$total_rows,$limit);
        $data = array(
            'examinationList'=>$examinationList,
            'page_links'=>$page_links,
            'per_page'=>$per_page
        );

        $this->load->view('/luckydog/examination/index',$data);
    }

    public function textures()
    {
        $login_status = $this->check_login_status();
        $id = $this->input->get("id",true)?$this->input->get("id",true):"";
        if ($login_status === FALSE){
            header("Location:login");
        }
        $_SESSION['v_menu'] = 'examination';
        $data = array();
        if(!empty($id)){
            $examinationInfo = $this->examination->getExaminationInfo($id);
            $data["examInfo"] = $examinationInfo;
        }
        $this->load->view("/luckydog/examination/set_exam", $data);
    }
    public function question()
    {
        $id = $this->input->get("id",true) ? $this->input->get("id",true) : 0;
        $questionList = $this->examination->getQuestion($id);
        foreach ($questionList as $key => $value) {
            if($value['questionType'] == 1)
            {
                $questionList[$key]['option'] = $this->examination->getOptionList($value['questionID']);
            }
        }
		$this->load->model('luckydog/News_model', 'news');
		$newsInfo = $this->news->getNewsInfobyID($id);
        $data = [
            'id'=>$id,
            'questionList'=>$questionList,
			'newsInfo'=>$newsInfo
        ];
        $this->load->view("/luckydog/examination/show", $data);
    }

    public function ruanwenquestion()
    {
        $id = $this->input->get("id",true) ? $this->input->get("id",true) : 0;
		$questionType = $this->input->get("questionType",true) ? $this->input->get("questionType",true) : 0;
        $questionList = $this->examination->getQuestion($id,['questionType'=>$questionType]);
        foreach ($questionList as $key => $value) {
            if($value['questionType'] == 1)
            {
                $questionList[$key]['option'] = $this->examination->getOptionList($value['questionID']);
            }
        }
        $this->load->model('luckydog/News_model', 'news');
        $newsInfo = $this->news->getNewsInfobyID($id);
        $data = [
            'id'=>$id,
            'questionList'=>$questionList,
            'newsInfo'=>$newsInfo,
			'tupianshenhe'=>$questionType == 4?1:0
        ];
        $this->load->view("/luckydog/examination/ruanwenQuestion", $data);
    }
	//发布
	public function publish()
	{
        $all_question_point = $this->input->post("all_question_point",true) ? $this->input->post("all_question_point",true) : 0;
        $all_question_money = $this->input->post("all_question_money",true) ? $this->input->post("all_question_money",true) : 0;
        $newsID = $this->input->post("id",true) ? $this->input->post("id",true) : 0;
		$activity_endtime = $this->input->post("activity_endtime",true) ? strtotime($this->input->post("activity_endtime",true)) : 0;
        $data = [
            'all_question_point'=>$all_question_point,
            'all_question_money'=>$all_question_money,
            'activity_endtime'=>($activity_endtime+3600*24),
            'ispublish'=>1
        ];
		$res = $this->examination->publish($newsID,$data);
        echo $res;
	}
    public function editQues()
    {
        $questionID = $this->input->get("questionID",true) ? $this->input->get("questionID",true) : 0;
		$id = $this->input->get("id",true) ? $this->input->get("id",true) : 0;
		$data['questionInfo'] = [];
		if($questionID)
		{
			$questionInfo = $this->examination->getQuestionById($questionID);
			if($questionInfo['questionType'] == 1)
			{
				//单选 获取选项
				$optionList = $this->examination->getOptionList($questionID);
				if($optionList)
				{
					$option = [];
					foreach($optionList as $row)
					{
						$option[] = $row['optionTitle'];
					}
					$questionInfo['option'] = implode("\n",$option);
					$questionInfo['answerindex'] = $questionInfo['answer']-1;
					$questionInfo['answerstr'] = $option[$questionInfo['answer']-1];
				}
			}
		}
		$data['questionInfo'] = $questionInfo;
		$data['id'] = $id;
    	$this->load->view("/luckydog/examination/edit_question",$data);
    }
    public function do_editQuestion()
    {
        $questionID = $this->input->post("questionID",true) ? $this->input->post("questionID",true) : 0;
        $questionType = $this->input->post("questionType",true) ? $this->input->post("questionType",true) : "";
        $questionTitle = $this->input->post("questionTitle",true) ? $this->input->post("questionTitle",true) : 0;
        $answer = $this->input->post("answer",true) ? $this->input->post("answer",true) : "";
        $optionTitle = $this->input->post("optionTitle",true) ? $this->input->post("optionTitle",true) : "";
        $single_question_point = $this->input->post("single_question_point",true) ? $this->input->post("single_question_point",true) : 0;
		$single_question_money = $this->input->post("single_question_money",true) ? $this->input->post("single_question_money",true) : 0;
        $newsID = $this->input->post("newsID",true) ? $this->input->post("newsID",true) : 0;
        
        $quesiontData['newsID'] = $newsID; 
        $quesiontData['questionType'] = $questionType; 
        $quesiontData['questionTitle'] = $questionTitle;
        $quesiontData['single_question_point'] = $single_question_point;
		$quesiontData['single_question_money'] = $single_question_money;
        if($questionID)
        {
            //编辑
            $quesiontData['answer'] = $answer;
            $res = $this->examination->editQuestion($questionID,$quesiontData);
            $this->examination->delOptionByQID($questionID);
            //添加单选题选项
            if($optionTitle)
            {
                $options = [];
                if($questionType == 1 && $optionTitle)
                {
                    $options = explode("\n",$optionTitle);
                }
                $optionData['questionID'] = $questionID; 
                foreach ($options as $key => $value) {
                    $optionData['optionTitle'] = $value;
                    $res = $this->examination->editOption(0,$optionData);
                }
            }

        }else{
            //添加题目相关
            $quesiontData['CreateTime'] = date("Y-m-d H:i:s",time()); 

            //添加单选和填空的正确答案
            $quesiontData['answer'] = $answer;
            $res = $this->examination->editQuestion(0,$quesiontData);

            //添加单选题选项
            if($optionTitle)
            {
                $options = [];
                if($questionType == 1 && $optionTitle)
                {
                    $options = explode("\n",$optionTitle);
                }
                $optionData['questionID'] = $res; 
                foreach ($options as $key => $value) {
                    $optionData['optionTitle'] = $value;
                    $res = $this->examination->editOption(0,$optionData);
                }
            }
            
        }
        echo $res;
    }

    //编辑广告
    public function edit(){
        $paperID = $this->input->post("id",true) ? $this->input->post("id",true) : 0;
        $paperTitle = $this->input->post("paperTitle",true) ? $this->input->post("paperTitle",true) : "";
        $data = array(
            "paperTitle"=>$paperTitle,
        );
        if(empty($id)){
            $data['createTime']=date("Y-m-d H:i:s",time());
        }
        $res = $this->examination->edit($paperID,$data);
        echo $res;
    }

//编辑上线下，删除状态
    public function editStatus(){
        $id = $this->input->post("id",true) ? $this->input->post("id",true) : 0;
        $onlinestatus = $this->input->post("onlinestatus",true) ? $this->input->post("onlinestatus",true) : "";
        $type = $this->input->post("type",true) ? $this->input->post("type",true) : 0;
        $data = array(
            "id"=>$id,
            "onlinestatus"=>$onlinestatus,
            "type"=>$type
        );
        $res =$this->examination->editStatus($data);
        echo $res;
    }

    public function upload_cover()
    {
        $this->load->library('Upload');
        $upload = new Upload();
        $file_name =$upload->execute($_FILES['Filedata']);

        $savepath='./upload/ad/'.date('Y-m-d').'/';
        $upload->set_upload_dir($savepath);
        if (!file_exists($savepath)){
            mkdir($savepath);
        }
        if(is_string($file_name))
        {
            $res=json_encode(array('code'=>1,'type'=>0,'file_name'=>$file_name));

            echo $res;
        }
        else
        {
            echo json_encode(array('code'=>-1));
        }
    }

    //删除状态
    public function delete(){
        $id = $this->input->post("id",true) ? $this->input->post("id",true) : 0;
        $res =$this->examination->delete($id);
        echo $res;
    }

     public function questionAll()
    {
        $_SESSION['v_menu'] = 'questionall';
        $per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 0;
        $questionType = $this->input->get("questionType",true) ? $this->input->get("questionType",true) : 0;
        $filter = ['questionType'=>$questionType];
        $limit = 20;
        $total_rows = $this->examination->getAllQuestionCnt($filter);
        $base_url = '/luckydog/examination/questionall?';
        $page_links = $this->create_page_links($base_url,$total_rows,$limit);
        $questionList = $this->examination->getAllQuestionList($filter,$per_page, $limit);
        foreach ($questionList as $key => $value) {
            if($value['questionType'] == 1)
            {
                $questionList[$key]['options'] = $this->examination->getOptionList($value['questionID']);
            }
        }
        $data = [
            'id'=>$id,
            'questionList'=>$questionList,
            'page_links'=>$page_links,
            'per_page'=>$per_page,
        ];
        $this->load->view("/luckydog/examination/show_all", $data);
    }
     public function ruanwen()
    {
        $_SESSION['v_menu'] = 'ruanwen';
        $per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 0;
        $questionType = $this->input->get("questionType",true) ? $this->input->get("questionType",true) : 0;
        $filter = ['questionType'=>$questionType];
        $limit = 20;
        $total_rows = $this->examination->getRuanwenCnt($filter);
        $base_url = '/luckydog/examination/ruanwen?';
        $page_links = $this->create_page_links($base_url,$total_rows,$limit);
        $fields = " newsID,title,addtime,isDel,onlinestatus,categoryid,point,ispublish,activity_endtime,totalmoney";
        $ruanwenList = $this->examination->getRuanwenList($filter,$per_page, $limit,$fields);
        foreach ($ruanwenList as $key => $ruanwen) {
            $ruanwenList[$key]['danxuanCnt'] = $ruanwenList[$key]['tiankongCnt'] = $ruanwenList[$key]['tupianCnt'] = 0;
            $questionList = $this->examination->getQuestion($ruanwen['newsID'],[]);
            foreach ($questionList as  $value) {
                if($value['questionType'] == 1)
                {
                    $ruanwenList[$key]['danxuanCnt'] += 1;
                }elseif ($value['questionType'] == 2) 
                {
                    $ruanwenList[$key]['tiankongCnt'] += 1;
                }else
                {
                    $ruanwenList[$key]['tupianCnt'] += 1;
                }
            }

            //获取已达人数
            $answeredUserCnt = $this->examination->getAnsweredUserCnt($ruanwen['newsID']);
            $ruanwenList[$key]['answeredUserCnt'] = $answeredUserCnt?$answeredUserCnt:0;

            //待审核数目
            $daishenheCnt = $this->examination->daishenheCnt($ruanwen['newsID']);
            $ruanwenList[$key]['daishenheCnt'] = $daishenheCnt?$daishenheCnt:0;

            //已发积分
            
            $sendPoints = $this->point->getSendPoints($ruanwen['newsID']);
            $ruanwenList[$key]['sendPoints'] = $sendPoints?$sendPoints:0;
            //已发金额
            
            $sendMoney = $this->point->getSendMoney($ruanwen['newsID']);
            $ruanwenList[$key]['sendMoney'] = $sendMoney?$sendMoney:0;
        }
        //print_r($ruanwenList);die;
        $data = [
            'id'=>$id,
            'ruanwenList'=>$ruanwenList,
            'page_links'=>$page_links,
            'per_page'=>$per_page,
        ];
        $this->load->view("/luckydog/examination/ruanwen", $data);
    }

    public function estimate()
    {
        $this->load->model('/luckydog/Point_model', 'point');
        $params['newsID'] = $this->input->post('newsID') ? $this->input->post('newsID') : 17;
        $params['questionID'] = $this->input->post('questionID') ? $this->input->post('questionID') : 58;
        $params['AccountID'] = $this->input->post('AccountID') ? $this->input->post('AccountID') : 58;
        $params['isright'] = $this->input->post('isright') ? $this->input->post('isright') : -1;
        $params['answerID'] = $this->input->post('answerID') ? $this->input->post('answerID') : 0;
        $validate = new Validate([
            'questionID' => 'require|number',
            'AccountID' => 'require|string',
            'newsID' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $data['code'] = 50003;
            $data['message'] = $validate->getError();
            echo json_encode($data);
            exit;
        }
        $result = [
            'isright'=>0,
            'single_question_point'=>0,
            'single_question_money'=>0,
            'allRightPoint'=>0,
            'allRightMoney'=>0,     
            ];
        //查询题目是否存在
        
        
        $answerData['ID'] = $params['answerID'];
        $answerData['questionID'] = $params['questionID'];
        $answerData['newsID'] = $params['newsID'];
        $answerData['AccountID'] = $params['AccountID'];
        //查询题目是否存在
        $questionInfo = $this->examination->getQuestionInfo_answer($params['questionID'],$params['newsID'],3);
        if(!$questionInfo)
        {
            $data['code'] = 80002;
            $data['message'] = $validate->getError();
            echo json_encode($data);
        }

        $this->load->model('luckydog/News_model', 'news');
        $totalMoney = $this->news->getTotalMoneyByNewsID($params['newsID']);
        if($questionInfo['totalmoney'] < ($totalMoney+$questionInfo['single_question_money']))
        {
            $data['code'] = 90009;
            $data['message'] = $validate->getError();
            echo json_encode($data);
        }

        $data['code'] = 200;
        $data['message'] = "成功";
        $answerID = $this->examination->updateAnswer($answerData,['isright'=>$params['isright']]);
        //单选填空添加积分
        if($answerID)
        {
            if($params['isright'] == 1)
            {
                 //添加积分
                if($questionInfo['single_question_point'])
                {
                    $pointData = [
                        'points'=>$questionInfo['single_question_point'],
                        'AccountID'=>$params['AccountID'],
                        'type'=>6,
                        'createtime'=>date("Y-m-d",time()),
                        'typeid'=>$params['questionID'],
                    ];      
                    $res = $this->point->addAnswerPoints($pointData);
                    if(!$res)
                    {
                        $data['code'] = 50006;
                        $data['message'] = $validate->getError();
                        echo json_encode($data);
                    }
                    $result['single_question_point'] = $questionInfo['single_question_point'];
                }
                
                                     //添加金钱
                if($questionInfo['single_question_money'])
                {
                    $pointData = [
                        'money'=>$questionInfo['single_question_money'],
                        'AccountID'=>$params['AccountID'],
                        'type'=>6,
                        'createtime'=>date("Y-m-d",time()),
                        'typeid'=>$params['questionID'],
                    ];      
                    $res = $this->point->addAnswerMoney($pointData);
                    if(!$res)
                    {
                        $data['code'] = 50006;
                        $data['message'] = $validate->getError();
                        echo json_encode($data);
                    }
                    $result['single_question_money'] = $questionInfo['single_question_money'];
                }
            }
            
            //判断每一道题是不是对的
            $fields = " ques.newsID,ques.questionID ,ques.questionTitle,ques.questionType,ques.CreateTime,ques.answer,ques.single_question_point,news.all_question_point";
            $questionList = $this->examination->getQuestionList_answer($params['newsID'],$fields);
            $allRight = 1;
            foreach($questionList as $qkey=>$value)
            {
                $answerInfo = $this->examination->checkQuestionAnswered($value['questionID'],$params['AccountID']);
                if(empty($answerInfo) || $answerInfo['isright'] == 1)
                {
                    $allRight = 0 ;                 
                }
            }
            if($allRight == 1)
            {
                 //添加积分
                $pointData = [
                    'points'=>$questionInfo['all_question_point'],
                    'AccountID'=>$params['AccountID'],
                    'type'=>6,
                    'createtime'=>date("Y-m-d",time()),
                    'typeid'=>$params['questionID'],
                ];      
                $res = $this->point->addAnswerPoints($pointData);
                $result['allRightPoint'] = $questionInfo['all_question_point'];
                
                 //添加积分
                $pointData = [
                    'money'=>$questionInfo['all_question_money'],
                    'AccountID'=>$params['AccountID'],
                    'type'=>6,
                    'createtime'=>date("Y-m-d",time()),
                    'typeid'=>$params['questionID'],
                ];      
                $res = $this->point->addAnswerMoney($pointData);
                $result['allRightMoney'] = $questionInfo['all_question_money'];
            }
            
        }else{
            $data['code'] = 50006;
            $data['message'] = $validate->getError();
            echo json_encode($data);
        }
        $data['data'] = $result;

        echo json_encode($data);exit;
    }


}
/* End of file index.php */
/* Location: ./application/controllers/luckydog/index.php */